<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Buygifts as BuygiftsMdl;
use app\admin\model\Product;

class Buygifts extends Base
{
    /**
     * 获取买赠商品列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }
        $where = [
            'a.status' => 1,
        ];

        $model = new BuygiftsMdl();
        $fields = 'a.buy_product_id as product_id, a.gift_product_id, a.buy_num, a.gift_num, a.to_user_type, a.to_users, a.range, a.store_ids, b.id, b.name, b.img_url, b.price, b.unit, b.spec, b.describe, b.type';
        $order = 'a.create_date DESC';
        $list = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.buy_product_id = b.id')->field($fields)->limit($start, $length)->order($order)->select();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '没有相关商品', '没有相关商品');
        }
        $total = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.buy_product_id = b.id')->count();

        foreach ($list as &$item) {
            $unitArr = get_product_unit();
            $item['unit'] = $unitArr[$item['unit']];
            // 库存
            $qty = Stock::getStock($item['id']);
            $item['qty'] = $qty;

            $item['to_users'] && $item['to_users'] = explode(',', $item['to_users']);
            // 赠送商品
            $item['gift_product_info'] = Product::where('id', $item['gift_product_id'])->field('name, price, unit')->find();
            $item['gift_product_info']['unit'] = $unitArr[$item['gift_product_info']['unit']];
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }
}